package com.beta.admin.controller;


import com.beta.admin.request.admin.AdminRequest;
import com.beta.common.web.ContentType;
import com.beta.service.IAdminsService;
import com.beta.admin.support.web.BaseController;
import com.beta.dto.admin.AdminDto;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by vector on 2016/12/29.
 */
@RestController
@RequestMapping(value = RequestMappingConstants.MAPPING_PREFIX + "/admins")
public class AdminController extends BaseController {

    @Autowired
    private IAdminsService adminsService;

    @RequiresPermissions("admins:list")
    @GetMapping(value = "", produces = {ContentType.JSON})
    public Object getAdmins(@RequestParam(defaultValue = "") String user) {
        return pageData(adminsService.getAdmins(user, getMybatisPage()));
    }

    @RequiresPermissions("admins:view")
    @GetMapping(value = "/{adminId}", produces = {ContentType.JSON})
    public Object getAdminById(@PathVariable("adminId") Integer adminId) {
        return ok(adminsService.getAdminById(adminId));
    }

    @RequiresPermissions("admins:add")
    @PostMapping(value = "", consumes = ContentType.JSON, produces = ContentType.JSON)
    public Object addAdmin(@Valid @RequestBody AdminRequest adminRequest) {
        AdminDto adminDto = new AdminDto();
        adminDto.setUsername(adminRequest.getUsername());
        adminDto.setEmail(adminRequest.getEmail());
        adminDto.setEncryptedPassword(BCrypt.hashpw(adminRequest.getPassword(), BCrypt.gensalt()));
        adminDto.setRoleId(adminRequest.getRoleId());
        adminDto.setCityCode(adminRequest.getCityCode());
        adminsService.executeCreateAdmin(adminDto);
        return null;
    }

    @RequiresPermissions("admins:edit")
    @PatchMapping(value = "/{adminId}", produces = {ContentType.JSON})
    public Object updateAdminById(@PathVariable("adminId") Integer adminId, @Valid @RequestBody AdminRequest adminRequest) {
        AdminDto adminDto = new AdminDto();
        adminDto.setUsername(adminRequest.getUsername());
        adminDto.setEmail(adminRequest.getEmail());
        adminDto.setEncryptedPassword(BCrypt.hashpw(adminRequest.getPassword(), BCrypt.gensalt()));
        adminDto.setRoleId(adminRequest.getRoleId());
        adminsService.executeUpdateAdmin(adminId, adminDto);
        return null;
    }

}
